package persistence

import (
	"Data-API-MCP/backend/internal/domain/entity"
	"Data-API-MCP/backend/internal/domain/repository"
	"context"
	"time"

	"gorm.io/gorm"
)

// AuditRepositoryImpl 审计日志仓储实现
type AuditRepositoryImpl struct {
	db *gorm.DB
}

// NewAuditRepository 创建审计日志仓储实例
func NewAuditRepository(db *gorm.DB) repository.AuditRepository {
	return &AuditRepositoryImpl{
		db: db,
	}
}

// Create 创建审计日志
func (r *AuditRepositoryImpl) Create(ctx context.Context, log *entity.AuditLog) error {
	return r.db.WithContext(ctx).Create(log).Error
}

// GetByID 根据ID获取审计日志
func (r *AuditRepositoryImpl) GetByID(ctx context.Context, id int64) (*entity.AuditLog, error) {
	var log entity.AuditLog
	err := r.db.WithContext(ctx).First(&log, id).Error
	return &log, err
}

// List 获取审计日志列表
func (r *AuditRepositoryImpl) List(ctx context.Context, userID int64, resource string, resourceID int64, startTime, endTime string, page, pageSize int) ([]*entity.AuditLog, int64, error) {
	query := r.db.WithContext(ctx).Model(&entity.AuditLog{})

	if userID > 0 {
		query = query.Where("user_id = ?", userID)
	}
	if resource != "" {
		query = query.Where("resource = ?", resource)
	}
	if resourceID > 0 {
		query = query.Where("resource_id = ?", resourceID)
	}
	if startTime != "" {
		query = query.Where("created_at >= ?", startTime)
	}
	if endTime != "" {
		query = query.Where("created_at <= ?", endTime)
	}

	// 获取总数
	var total int64
	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	var logs []*entity.AuditLog
	err = query.Order("created_at DESC").
		Offset((page - 1) * pageSize).
		Limit(pageSize).
		Find(&logs).Error

	return logs, total, err
}

// Delete 删除审计日志
func (r *AuditRepositoryImpl) Delete(ctx context.Context, id int64) error {
	return r.db.WithContext(ctx).Delete(&entity.AuditLog{}, id).Error
}

// DeleteByTime 根据时间范围删除审计日志
func (r *AuditRepositoryImpl) DeleteByTime(ctx context.Context, before time.Time) error {
	return r.db.WithContext(ctx).Where("created_at < ?", before).Delete(&entity.AuditLog{}).Error
}
